package com.ruoyi.aimodel.controller;

import com.ruoyi.aimodel.domain.AipptOutline;
import com.ruoyi.aimodel.service.DeepSeekService;
import com.ruoyi.aimodel.service.IEwcCourseplanService;
import com.ruoyi.aimodel.service.IEwcCourseplanTeachingService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;

@RestController
@RequestMapping("/api")
public class DeepSeekController {
    private static final Logger logger = Logger.getLogger(DeepSeekController.class.getName());
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(DeepSeekController.class);

    @Autowired
    private DeepSeekService deepSeekService;
    @Autowired
    private IEwcCourseplanTeachingService ewcCourseplanTeachingService;
    @Autowired
     private IEwcCourseplanService ewcCourseplanService;

    @GetMapping(value = "/chatStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatStream(@RequestParam String message,@RequestParam String userid) {
        SseEmitter emitter = new SseEmitter(180000L);
        try {
            logger.info("开始处理userId的请求： " + userid + ", message: " + message);
            deepSeekService.callDeepSeekStream(userid, message)
                    .subscribe(
                            content -> {
                                try {
                                    emitter.send(content, MediaType.TEXT_PLAIN);
                                } catch (IOException e) {
                                    logger.severe("发送内容错误: " + e.getMessage());
                                    emitter.completeWithError(e);
                                }
                            },
                            error -> {
                                try {
                                    logger.severe("处理出现异常: " + error.getMessage());
                                    emitter.send(SseEmitter.event().data("Error: " + error.getMessage()));
                                } catch (IOException e) {
                                    logger.severe("发送了异常信息: " + e.getMessage());
                                    emitter.completeWithError(e);
                                } finally {
                                    emitter.complete();
                                }
                            },
                            () -> {
                                logger.info("该用户请求已处理完成 userId: " + userid);
                                emitter.complete();
                            }
                    );
        } catch (Exception e) {
            try {
                logger.severe("Unexpected error: " + e.getMessage());
                emitter.send(SseEmitter.event().data("Error: " + e.getMessage()));
            } catch (IOException ex) {
                logger.severe("Error sending unexpected error message: " + ex.getMessage());
                emitter.completeWithError(ex);
            } finally {
                emitter.complete();
            }
        }

        return emitter;
    }

    @GetMapping("/chat")
    public String chat(@RequestParam("message") String message,@RequestParam("userid") String userid) {
        String aa=deepSeekService.callDeepSeek(userid,message);
        log.info(aa);
        return aa;
    }




    @PostMapping("/aippt_outline")
    public SseEmitter aipptOutline(@Valid @RequestBody AipptOutline aipptOutline) {
        String model=",请按以下格式生成规划，需要生成规划的材料为：单元名称(@target1@)、课时名称(@target2@)、备注(@target3@)，不要添加开头和结尾，仅返回核心内容，不要返回描述，其中主题返回一个，二级标题至少返回5个，每个二级标题至少返回3个三级标题\n" +
                "# 主题\n" +
                "\n" +
                "## 二级标题\n" +
                "### 三级标题\n" +
                "- 具体条目";
        String  queryAiPptMsg =ewcCourseplanTeachingService.queryAiPptMsg(aipptOutline);
        String msg=model.replace("@target1@",aipptOutline.getCourseName())
                        .replace("@target2@",aipptOutline.getChapterName())
                        .replace("@target3@",aipptOutline.getContent());
        msg= msg+queryAiPptMsg;
        SseEmitter emitter = new SseEmitter(180000L);
        try {
            deepSeekService.callDeepSeekStreamAipptOutline(UUID.randomUUID().toString(), msg)
                    .subscribe(
                            content -> {
                                try {
                                    emitter.send(content, MediaType.TEXT_PLAIN);
                                } catch (IOException e) {
                                    logger.severe("发送内容错误: " + e.getMessage());
                                    emitter.completeWithError(e);
                                }
                            },
                            error -> {
                                try {
                                    logger.severe("处理出现异常: " + error.getMessage());
                                    emitter.send(SseEmitter.event().data("Error: " + error.getMessage()));
                                } catch (IOException e) {
                                    logger.severe("发送了异常信息: " + e.getMessage());
                                    emitter.completeWithError(e);
                                } finally {
                                    emitter.complete();
                                }
                            },
                            () -> {
                                emitter.complete();
                            }
                    );
        } catch (Exception e) {
            try {
                logger.severe("Unexpected error: " + e.getMessage());
                emitter.send(SseEmitter.event().data("Error: " + e.getMessage()));
            } catch (IOException ex) {
                logger.severe("Error sending unexpected error message: " + ex.getMessage());
                emitter.completeWithError(ex);
            } finally {
                emitter.complete();
            }
        }
        return emitter;
    }

//    @PostMapping("/aippt")
//    public String aippt(@Valid @RequestBody AipptOutline aipptOutline) {
//        String model="@target@，将上述内容按照如下格式生成，不需要开头```json和结尾```：\n" +
//                "\t{   \"type\": \"cover\",  \"data\": {    \"title\": \"主标题文本\",      \"text\":  \"副标题文本\"    }}\n" +
//                "\t{  \"type\": \"contents\",  \"data\": {    \"items\": [                \"目录条目1\",              \"目录条目2\"           ]  }}\n" +
//                "\t{  \"type\": \"transition\",  \"data\": {    \"title\": \"二级标题\",     \"text\":  \"描述性文案\"  }}\n" +
//                "\t{  \"type\": \"content\",  \"data\": {    \"title\": \"三级标题\",      \"items\": [               {        \"title\": \"子标题\",          \"text\":  \"描述文本\"        },      {                         \"title\": \"父级标题\",        \"items\": [               {            \"title\": \"子级标题\",            \"text\": \"描述文本\"          }        ]      }    ]  }}\n" +
//                "\t{ \"type\": \"end\" }\n" +
//                "\t格式说明：\n" +
//                "\t层级关系：cover → 主题封面contents → 目录页(对应所有transition标题)transition → 二级章节标题content → 三级内容模块end → 文档结束。\n" +
//                "\t标识嵌套规则：content页支持多级嵌套，通过items数组实现每级子项必须包含title，且至少包含text或items中的一个属性";
//        String msg=model.replace("@target@",aipptOutline.getContent());
//        String aa=deepSeekService.callDeepSeek(UUID.randomUUID().toString(),msg);
//        log.info(aa);
//        return aa;
//    }


    @PostMapping("/aippt")
    public SseEmitter aippt(@Valid @RequestBody AipptOutline aipptOutline) {
        String model="@target@，将上述内容按照如下json格式生成，开头不需要```json和结尾不需要```，：\n" +
                "\t{   \"type\": \"cover\",  \"data\": {    \"title\": \"主标题文本\",      \"text\":  \"副标题文本\"    }}\n" +
                "\t{  \"type\": \"contents\",  \"data\": {    \"items\": [                \"目录条目1\",              \"目录条目2\"           ]  }}\n" +
                "\t{  \"type\": \"transition\",  \"data\": {    \"title\": \"二级标题\",     \"text\":  \"描述性文案\"  }}\n" +
                "\t{  \"type\": \"content\",  \"data\": {    \"title\": \"三级标题\",      \"items\": [               {        \"title\": \"子标题\",          \"text\":  \"描述文本\"        },      {                         \"title\": \"父级标题\",        \"items\": [               {            \"title\": \"子级标题\",            \"text\": \"描述文本\"          }        ]      }    ]  }}\n" +
                "\t{ \"type\": \"end\" }\n" +
                "\t格式说明：\n" +
                "\t层级关系：cover → 主题封面contents → 目录页(对应所有transition标题)transition → 二级章节标题content → 三级内容模块end → 文档结束。\n" +
                "\t标识嵌套规则：content页支持多级嵌套，通过items数组实现每级子项必须包含title，且至少包含text或items中的一个属性";
        String msg=model.replace("@target@",aipptOutline.getContent());
        String  queryAiPptMsg =ewcCourseplanTeachingService.queryAiPptMsg(aipptOutline);
        msg= "请严格遵守开头不需要```json和结尾不需要```这条规则，生成完后自己也检查一下是否有问题，有问题的话重新生成"+msg+queryAiPptMsg;
        SseEmitter emitter = new SseEmitter(180000L);
        try {
            deepSeekService.callDeepSeekStreamAippt(UUID.randomUUID().toString(), msg)
                    .subscribe(
                            content -> {
                                try {
                                    emitter.send(content, MediaType.TEXT_PLAIN);
                                } catch (IOException e) {
                                    logger.severe("发送内容错误: " + e.getMessage());
                                    emitter.completeWithError(e);
                                }
                            },
                            error -> {
                                try {
                                    logger.severe("处理出现异常: " + error.getMessage());
                                    emitter.send(SseEmitter.event().data("Error: " + error.getMessage()));
                                } catch (IOException e) {
                                    logger.severe("发送了异常信息: " + e.getMessage());
                                    emitter.completeWithError(e);
                                } finally {
                                    emitter.complete();
                                }
                            },
                            () -> {
                                emitter.complete();
                            }
                    );
        } catch (Exception e) {
            try {
                logger.severe("Unexpected error: " + e.getMessage());
                emitter.send(SseEmitter.event().data("Error: " + e.getMessage()));
            } catch (IOException ex) {
                logger.severe("Error sending unexpected error message: " + ex.getMessage());
                emitter.completeWithError(ex);
            } finally {
                emitter.complete();
            }
        }
        return emitter;
    }



}